package com.sn.author.monitor;

import com.alibaba.fastjson.JSON;
import com.sn.author.common.enums.TaskEnums;
import com.sn.author.common.enums.TaskTypeEnum;
import com.sn.author.service.impl.TaskServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author xiaom
 * @Date 2020/9/22 14:43
 * @Version 1.0.0
 * @Description <工作线程管理器>
 **/
@Slf4j
public class WorkerManage {

    //任务类型集合
    private static List<String> _TASK_KEYS;

    //线程管理 key - 任务类型 value - 工作线程
    private volatile static HashMap<String, List<Thread>> _THREAD_MANAGE_CACHE = new HashMap<>();

    //工作线程数量
    private static final Integer _THREAD_CNT = 1;


    static{
        _TASK_KEYS = Arrays.stream(TaskTypeEnum.values()).map(s -> TaskServiceImpl.parserKey(s.getType())).collect(Collectors.toList());
        log.info("初始化任务类型完毕. --> {}", JSON.toJSONString(_TASK_KEYS));
        try {
            buildWorker();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static synchronized void buildWorker() throws Exception {
        if(_TASK_KEYS.isEmpty()){
            throw new Exception("系统异常,请重启服务器");
        }

        List<Thread> threads;
        for (String taskKey : _TASK_KEYS) {
            threads = new ArrayList<>();
            for (int i = 0; i < _THREAD_CNT; i++){
                Thread thread = new TaskListenerHandler(taskKey);
                threads.add(thread);
                thread.start();
                _THREAD_MANAGE_CACHE.put(taskKey,threads);
            }
        }
    }
}
